package com.Ohuang.myrefrsh;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ohuang.refresh.OhRefreshLayout;
import com.ohuang.refresh.OnRefreshListener;
import com.ohuang.refresh.Refresh;
import com.ohuang.refresh.TextRefreshView;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private OhRefreshLayout ohRefreshLayout;
    private List<String> list = new ArrayList<>();
    private ExecutorService executorService = Executors.newCachedThreadPool();
    private TextAdapter textAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.rv_main);
        ohRefreshLayout = findViewById(R.id.refresh);
        for (int i = 0; i < 10; i++) {
            list.add("这是第" + i + "条消息");
        }

        textAdapter = new TextAdapter(this, list);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(textAdapter);
        ohRefreshLayout.setTopFreshView(new TextRefreshView(this));
        ohRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(Refresh refresh) {
                executorService.execute(runnable1);
            }

            @Override
            public void onBottomRefresh(Refresh refresh) {
                executorService.execute(runnable2);
            }
        });



    }

    Runnable runnable1 = new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    list.add(0, "这是新数据");
                    textAdapter.notifyDataSetChanged();
                    ohRefreshLayout.release();
                }
            });
        }
    };

    Runnable runnable2 = new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    list.add( "这是更多数据");
                    textAdapter.notifyDataSetChanged();
                    ohRefreshLayout.refreshComplete();
                }
            });
        }
    };
}